﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Elmah;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;
namespace Viettel.VOFFICE.Web.Controllers
{
    public class LibraryController : BaseController
    {

        [HttpPost]
        [ActionName("upload_file")]
        public JsonResult UploadFile(string qqfile, string folder = "/UploadAttachment/")
        {
            List<ValidationResult> outError;
            if (string.IsNullOrEmpty(folder))
            {
                return Json(new { success = false, message = "Không tìm thấy thư mục để lưu tệp tải lên" });
            }
            var path = Server.MapPath("~" + folder);
            var direction = new DirectoryInfo(path);
            if (!direction.Exists)
            {
                direction.Create();
            }
            string fileName;
            var uri = Request.Url;
            var requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
            var stream = Request.InputStream;
            var guid = Guid.NewGuid();
            string file;
            if (String.IsNullOrEmpty(Request["qqfile"]))
            {
                //fix IE
                HttpPostedFileBase postedFile = Request.Files[0];
                Debug.Assert(postedFile != null, "postedFile != null");
                stream = postedFile.InputStream;
                fileName = string.Format(@"{0}{1}", guid.ToString(), Path.GetExtension(Request.Files[0].FileName));
                file = Path.Combine(path, fileName);
            }
            else
            {
                //firefox, chrome
                fileName = string.Format(@"{0}{1}", guid.ToString(), qqfile.GetFileExtension());
                file = Path.Combine(path, fileName);
            }

            var fileModel = new UploadFileModel()
            {
                FileContent = stream,
                FilePath = file,
                FileName = fileName
            };

            if (fileModel.IsValid(out outError))
            {
                try
                {
                    var buffer = new byte[fileModel.FileContent.Length];
                    stream.Read(buffer, 0, buffer.Length);
                    System.IO.File.WriteAllBytes(fileModel.FilePath, buffer);
                }
                catch (Exception ex)
                {
                    return Json(new { success = false, message = ex.Message }, "application/json");
                }

                return Json(new { success = true, path = requested + folder + fileName }, "text/html");
            }
            else
            {
                return Json(new { success = false, message = string.Join(", ", outError) }, "application/json");
            }
        }
        // lấy tất cả
        [HttpGet]
        [ActionName("get_all")]
        public JsonResult GetAll(int pageIndex = 0, int pageSize = 0)
        {
            try
            {
                if (pageIndex >= 0 && pageSize > 0)
                {
                    var list = unitOfWork.LibraryRepository.GetPaging(pageIndex, pageSize);
                    return Json(new JsonResponse()
                                    {
                                        Status = true,
                                        Result = new
                                                     {
                                                         PageIndex = list.PageIndex,
                                                         PageSize = list.PageSize,
                                                         PageCount = list.PageCount,
                                                         List = list.Select(o => new LibraryModel(o))
                                                     }
                                    }, JsonRequestBehavior.AllowGet);
                }

                else
                {
                    var list = unitOfWork.LibraryRepository.Get().Select(o => new LibraryModel(o));
                    return Json(new JsonResponse() { Status = true, Result = list }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {

                ErrorSignal.FromCurrentContext().Raise(new NotSupportedException("", ex));
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
            }

        }

        [HttpPost]
        [ActionName("add")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult Add(LibraryModel library)
        {
            try
            {
                try
                {
                    List<ValidationResult> outError;
                    if (!library.IsValid(out outError))
                    {
                        return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                        });
                    } //end ìf
                    else
                    {
                        var data = new Library
                        {
                            //Id = metaData.Id,
                            Name = library.Name,
                            AttachmentPath = library.AttachmentPath,
                            AttachmentName = library.AttachmentName,
                            IsActive = library.IsActive,
                            CreatorId = library.CreatorId,
                            Description = library.Description,
                            IsSubmission = library.IsSubmission,
                            RelateToId = library.RelateToId,
                            CreatedAt = DateTime.Now,
                            UpdatedAt = DateTime.Now,
                        };
                        unitOfWork.LibraryRepository.Insert(data);
                        return Json(SimplyResponse.ResposeWithId(data.Id));
                    }
                }
                catch (Exception ex)
                {
                    return Json(SimplyResponse.Response500());
                    //throw;
                }
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }
        //cập nhật
        [HttpPut]
        [ActionName("update")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult Update(LibraryModel library, string modified = "all")
        {
            try
            {
                List<ValidationResult> outError;
                if (library.IsValid(out outError))
                {
                    var dblibrary = unitOfWork.LibraryRepository.GetById(library.Id);
                    if (dblibrary == null)
                    {
                        return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = "không sửa đc!"
                        });
                    }
                    if (modified.ToUpper().Contains("ISACTIVE"))
                    {
                        dblibrary.IsActive = library.IsActive;
                    }
                    else if (modified.ToUpper().Contains("ISSUBMISSION"))
                    {
                        dblibrary.IsSubmission = library.IsSubmission;
                    }
                    else//cập nhập hết
                    {
                        dblibrary.Name = library.Name;
                        dblibrary.AttachmentPath = library.AttachmentPath;
                        dblibrary.IsSubmission = library.IsSubmission;
                        dblibrary.IsActive = library.IsActive;
                        dblibrary.AttachmentName = library.AttachmentName;
                        dblibrary.Description = library.Description;
                        dblibrary.RelateToId = library.RelateToId;
                        dblibrary.CreatorId = library.CreatorId;
                    }//end if
                    dblibrary.UpdatedAt = DateTime.Now;
                    dblibrary.CreatedAt = DateTime.Now;
                    unitOfWork.LibraryRepository.Update(dblibrary);
                    return Json(SimplyResponse.Response200());
                }
                else
                {
                    return Json(new JsonResponse()
                    {
                        Status = false,
                        Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                    });
                }//end ìf
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }
        //xóa
        [HttpPost]
        [ActionName("delete")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult Delete(int id)
        {
            try
            {
                unitOfWork.LibraryRepository.Delete(id);
                return Json(SimplyResponse.Response200());
            }
            catch (Exception)
            {

                return Json(SimplyResponse.Response500());
            }
        }

        [HttpPost]
        [ActionName("save")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult Save(LibraryModel model)
        {
            List<ValidationResult> validation;
            if (model != null && model.IsValid(out  validation))
            {
                try
                {
                    var library = new Library()
                                      {
                                          Name = model.Name
                                      };
                    if (model.Id > 0)
                    {
                        unitOfWork.LibraryRepository.Update(library);
                    }
                    else
                    {
                        unitOfWork.LibraryRepository.Insert(library);
                    }
                    return Json(SimplyResponse.Response200());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                    return Json(SimplyResponse.Response200());
                }
            }
            else
            {
                return Json(new JsonResponse()
                                {
                                    Status = false,
                                    Result = "Không thể thêm mới"
                                });
            }
        }
    }
}
